extends Node2D
class_name BattleFieldUnit

@export var id = ""
@onready var animatedSprite2D: AnimatedSprite2D = $AnimatedSprite2D
@onready var placeHolder: Control = $PlaceHolder
@onready var stateMachine: StateMachine = $StateMachine

var charConfig = null
var charData = null
var isEnemy = false
var currentMovePath:Array
var currentMoveTarget = null
var currentMoveDirection = Vector2.ZERO
var moveSpeed = 60


signal onMoveArriveTarget


func _ready() -> void:
	placeHolder.visible = false
	
	if id:
		initById()
		
	
func _physics_process(delta: float) -> void:
	stateMachine.run(delta)
	

func initById():
	charConfig = ConfigClasses.CharacterConfig.idConfigDict[id]
	
	charData = CustomClasses.CharData.new()
	charData.initByCharConfig(id)
	
	initSpriteFrames()
	animatedSprite2D.play("idle")


func initSpriteFrames():
	var ss = ResourcePreload.resources["bu_" + id]
	animatedSprite2D.sprite_frames = ss


func initByCharData(_charData):
	charConfig = _charData.charConfig
	charData = _charData
	id = charConfig.id
	
	initSpriteFrames()
	animatedSprite2D.play("idle")
	

func setCell(cell):
	var targetPos = GlobalUtils.cell2Pos(cell)
	position = targetPos
	

func getCell():
	return GlobalUtils.pos2Cell(position)
	

func setIsEnemy(b):
	isEnemy = b


func setReady():
	stateMachine.clearAndAddState(Consts.STATE_BATTLEFIELD_UNIT_READY)
	

func setIdle():
	stateMachine.clearAndAddState(Consts.STATE_BATTLEFIELD_UNIT_IDLE)
	
	
func movePath(path:Array):
	currentMovePath = path.duplicate(false)
	stateMachine.clearAndAddState(Consts.STATE_BATTLEFIELD_UNIT_MOVE)
	

func processMove(delta):
	if not currentMoveTarget and currentMovePath.size() > 0:
		currentMoveTarget = currentMovePath.pop_front()
		currentMoveDirection = (currentMoveTarget - getCell()).normalized()
		
	if currentMoveTarget and is_equal_approx(GlobalUtils.cell2Pos(currentMoveTarget).distance_to(position), 0):
		position = GlobalUtils.cell2Pos(currentMoveTarget)
		currentMoveTarget = null
		
		if currentMovePath.size() <= 0:
			onMoveArriveTarget.emit(self)
			
		return
		
	if not currentMoveTarget: return
	
	var targetPos = GlobalUtils.cell2Pos(currentMoveTarget)
	position = position.move_toward(targetPos, moveSpeed * delta)
	
	updateMoveAnimationByCurrentMoveDirection()
	

func updateMoveAnimationByCurrentMoveDirection():
	if currentMoveDirection == Vector2.LEFT:
		animatedSprite2D.play("moveLeft")
	if currentMoveDirection == Vector2.UP:
		animatedSprite2D.play("moveUp")
	if currentMoveDirection == Vector2.RIGHT:
		animatedSprite2D.play("moveRight")
	if currentMoveDirection == Vector2.DOWN:
		animatedSprite2D.play("moveDown")
	
